package xj.graph2d.command;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import xj.graph2d.Command;
import xj.graph2d.DrawCanvas;
import xj.graph2d.SimpleDrawDocument;
import xj.graph2d.SimpleDrawView;

public abstract class AbstractCommand implements Command {

  protected AbstractCommand(SimpleDrawView view, SimpleDrawDocument doc) {
    this.doc = doc;
    this.view = view;
    if (view != null) {
      canvas = view.getCanvas();
    }
  }

  public boolean isSignificant() {
    return true;
  }

  public void addAuxActions(List<Command.AuxAction> alist) {
    if (alist != null && alist.size() > 0) {
      if (auxActions == null) {
	auxActions = new ArrayList<Command.AuxAction>(4);
      }
      Iterator<Command.AuxAction> iter = alist.iterator();
      while (iter.hasNext()) {
	AuxAction o = iter.next();
	auxActions.add(o);
      }
    }
  }

  public void addAuxAction(AuxAction ac) {
    if (ac != null) {
      if (auxActions == null) {
	auxActions = new ArrayList<Command.AuxAction>(4);
      }
      auxActions.add(ac);
    }
  }

  @Override
  public String toString() {
    return getClass().getName();
  }

  protected void auxForward() {
    if (auxActions != null) {
      int n = auxActions.size();
      for (int i = 0; i < n; i++) {
	AuxAction ac = auxActions.get(i);
	ac.forward();
      }
    }
  }

  protected void auxBackward() {
    if (auxActions != null) {
      int n = auxActions.size();
      for (int i = n - 1; i >= 0; i--) {
	AuxAction ac = auxActions.get(i);
	ac.backward();
      }
    }
  }

  protected void auxBackward(boolean after) {
    if (auxActions != null) {
      int n = auxActions.size();
      for (int i = n - 1; i >= 0; i--) {
	AuxAction ac = auxActions.get(i);
	if (ac.isAlwaysAfter() == after) {
	  ac.backward();
	}
      }
    }
  }

  protected SimpleDrawView view;

  protected SimpleDrawDocument doc;

  protected DrawCanvas canvas;

  protected List<Command.AuxAction> auxActions;

  protected boolean isCommandSet = false;

}
